<?php
namespace app\post\controller\admin;
use app\admin\model\user\User;
use app\common\controller\Admin;
use app\common\traits\ControllerCurd;
use app\post\model\UseLookAccess;
use think\Db;
use think\Request;
use app\common\annotation\NodeAnnotation;
/**
 * @NodeAnnotation(
 *     title="文章模块",
 *     parent="post/admin.index",
 *     is_menu=0,
 *     is_view=0,
 *     auth=1,
 * )
 */
class Post extends Admin
{
    use ControllerCurd;
    public $model = '';
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\post\model\Post();
    }

    /**
     * @NodeAnnotation(
     *     title="文章管理",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index"
     * )
     */
    public function index(Request $request)
    {
        $keywords  = $request->param("keywords");

        $where = [];

        if($keywords) array_push($where,['post_title',"like","%$keywords%"]);
        $postList = $this->model->where($where)
            ->with("category,tag,user")
            ->order("update_time","desc")
            ->paginate();

        $this->assign([
            "postList"=> $postList,
            "search"  => [
                "keywords" => $keywords
            ]
        ]);
        return view();
    }

    /**
     * @NodeAnnotation(
     *     title="添加文章",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function addpost(Request $request)
    {
        if($request->isAjax())
        {
            $tree = $request->param("dataType");
            if($tree=='tree')
            {
                $categoryList = (new \app\post\model\Category())->select();
                return json($categoryList);
            }
            $input = $request->post();
            $input['post_content'] = cmf_replace_content_file_url($request->post("post_content"),true);

        }



        $this->add(url("post/admin.post/index"),function($model,$data){
            //关联分类
            if(isset($data['category_id']) && !empty($data['category_id']))
            {
                $categoryIdList = explode(',',$data['category_id']);
                foreach ($categoryIdList as $v)
                {
                    //查重
                    $result = Db::name("portal_category_post")
                        ->where("category_id",$v)
                        ->where("post_id",$data['id'])
                        ->find();
                    if(!$result)
                    {
                        $result = Db::name("portal_category_post")->insert([
                            'post_id'     => $data['id'],
                            'category_id' => $v,
                            'list_order'  => 10000,
                            'status'      => 1
                        ]);
                    }
                    if($result)
                    {
                        (new \app\post\model\Category())->where("id",$v)->setInc("post_count");
                    }
                }
            }
            //tag 标签
            if(isset($data['post_keywords']) && !empty($data['post_keywords']))
            {
                $tagList = explode(",",$data['post_keywords']);
                foreach ($tagList as $item)
                {
                    $tagId = 0;
                    $tag = (new \app\post\model\Tag())->where("name",$item)->find();
                    if($tag)
                    {
                        $tagId = $tag['id'];
                    }else{
                        $tags = \app\post\model\Tag::create([
                            "name"       => $item,
                            "status"     => 1,
                            "recommended"=> 1,
                            "post_count" => 0,
                        ]);
                        $tagId = $tags->id;
                    }
                    $result =  Db::name('portal_tag_post')->where("tag_id",$tagId)
                        ->where("post_id",$data['id'])
                        ->find();
                    if(!$result)
                    {
                        $result = Db::name('portal_tag_post')->insert([
                            "tag_id" => $tagId,
                            "post_id"=> $data['id'],
                            "status" => 1
                        ]);
                    }
                    if($result)
                    {
                        \app\post\model\Tag::where("name",$item)->setInc("post_count");
                    }
                }
            }
        },isset($input)?$input:[]);
        return view();
    }

    /**
     * @NodeAnnotation(
     *     title="编辑文章",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function editpost(Request $request, $id=0)
    {
        $post = $this->model->with('user,category,tag')->find($id);
        $post['post_content'] = cmf_replace_content_file_url($post['post_content'],false);

        if(empty($post['document_type']) and $post['document_type']=='')
        {
            $post['document_type'] = [];
        }else{
            $post['document_type'] = explode(",",$post['document_type']);
        }

        //分类id 处理
        if(isset($post['category']))
        {
            $cateList = $post['category']->toArray();
            $post['categoryIdList'] = implode(',',array_column($cateList,'id'));
            $post['categoryNameLst'] = implode(',',array_column($cateList,'name'));
        }
        if(isset($post['tag']))
        {
            $post['tagIdList'] = implode(',',array_column($post['tag']->toArray(),'id'));
        }

        if($request->post())
        {
            $input = $request->post();
            $input['post_content'] = cmf_replace_content_file_url($request->post("post_content"),true);

            if(empty($input['post_status'])) $input['post_status'] = 0;
            if(empty($input['recommended'])) $input['recommended'] = 0;
            if(empty($input['is_top'])) $input['is_top'] = 0;

            if(!isset($input['document_type']))
            {
                $input['document_type'] = "";
            }else{
                $input['document_type'] = implode(",",$input['document_type']);
            }
        }

        $this->edit(url("post/admin.post/index"),function($model,$data){
            //关联分类
            if(isset($data['category_id']) && !empty($data['category_id']))
            {
                $categoryIdList = explode(',',$data['category_id']);
                $cateResult = Db::name("portal_category_post")
                    ->where("post_id",$data['id'])
                    ->select();
                if($cateResult)
                {
                    Db::name("portal_category_post")
                        ->where("id",'in', array_column($cateResult,'id'))
                        ->delete();
                    (new \app\post\model\Category())->where("id",'in',array_column($cateResult,'category_id'))
                        ->where("post_count","neq",0)
                        ->setDec("post_count");
                }
                foreach ($categoryIdList as $v)
                {
                    //查重
                    $result = Db::name("portal_category_post")
                        ->where("category_id",$v)
                        ->where("post_id",$data['id'])
                        ->find();
                    if(!$result)
                    {
                        $result = Db::name("portal_category_post")->insert([
                            'post_id'     => $data['id'],
                            'category_id' => $v,
                            'list_order'  => 10000,
                            'status'      => 1
                        ]);
                    }
                    if($result)
                    {
                        (new \app\post\model\Category())->where("id",$v)->setInc("post_count");
                    }
                }
            }
            //tag 标签
            if(isset($data['post_keywords']) && !empty($data['post_keywords']))
            {
                $tagList = explode(",",$data['post_keywords']);
                $tagResult = Db::name("portal_tag_post")
                    ->where("post_id",$data['id'])
                    ->select();
                if($tagResult)
                {
                    Db::name("portal_tag_post")
                        ->where("id",'in', array_column($tagResult,'id'))
                        ->delete();
                    (new \app\post\model\Tag())->where("id",'in',array_column($tagResult,'tag_id'))
                        ->where("post_count","neq",0)
                        ->setDec("post_count");
                }
                foreach ($tagList as $item)
                {
                    $tagId = 0;
                    $tag = (new \app\post\model\Tag())->where("name",$item)->find();
                    if($tag)
                    {
                        $tagId = $tag['id'];
                    }else{
                        $tags = \app\post\model\Tag::create([
                            "name"       => $item,
                            "status"     => 1,
                            "recommended"=> 1,
                            "post_count" => 0,
                        ]);
                        $tagId = $tags->id;
                    }
                    $result =  Db::name('portal_tag_post')->where("tag_id",$tagId)
                        ->where("post_id",$data['id'])
                        ->find();
                    if(!$result)
                    {
                        $result = Db::name('portal_tag_post')->insert([
                            "tag_id" => $tagId,
                            "post_id"=> $data['id'],
                            "status" => 1
                        ]);
                    }
                    if($result)
                    {
                        \app\post\model\Tag::where("name",$item)->setInc("post_count");
                    }
                }
            }
        },isset($input)?$input:[]);
        $this->assign([
            "post"         => $post,
            //"categoryList" => $categoryList
        ]);
        return view();
    }

    /**
     * @NodeAnnotation(
     *     title="删除文章",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function delpost()
    {
        $this->del('',function($model,$data){
            $catePost = Db::name('portal_category_post')
                ->where("post_id","in",$data)
                ->select();
            $tagPost =  Db::name('portal_tag_post')
                ->where("post_id","in",$data)
                ->select();
            if($catePost)
            {
                Db::name('portal_category_post')->where("id",'in',array_column($catePost,'id'))->delete();
                \app\post\model\Category::where('id','in',array_column($catePost,'category_id'))->setDec('post_count');
            }
            if($tagPost)
            {
                Db::name('portal_tag_post')->where("id",'in',array_column($tagPost,'id'))->delete();
                \app\post\model\Tag::where('id','in',array_column($tagPost,'tag_id'))->setDec('post_count');
            }
        });
    }

    /**
     * @NodeAnnotation(
     *     title="设置查看权限",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function set_look_access()
    {
        $article_id = $this->request->param("article_id",0,"intval");
        $accessType = $this->request->param("access_type",0,'intval');
        if(!$article_id) $this->error("请选择所需要设置的文章");

        /**
         * 权限类型
         * 0：全部开放，
         * 1、登录用户，
         * 2、部分用户，
         * 3、会员用户
         */
         $result = $this->model->where("id",$article_id)->update([
                "access_type" => $accessType
            ]);
        /**
         * 对部分用户支持
         */
        $userId = $this->request->param("user_id",0,"intval");
        if($userId!==0)
        {
            $actionType = $this->request->param("action");

            $this->model = new UseLookAccess();

            $data = $this->model->where("user_id",$userId)
                ->where("article_id",$article_id)
                ->find();
            if($data)
            {
                //存在修改
                if($actionType==1 || $actionType==true)
                {
                    $this->model->where("user_id",$userId)
                        ->where("article_id",$article_id)
                        ->update([
                            "user_id"   => $userId,
                            "article_id"=> $article_id
                        ]);
                }
                //删除操作
                if ($actionType==0 || $actionType==false)
                {
                    $this->model->where("user_id",$userId)
                        ->where("article_id",$article_id)
                        ->delete();
                }
            }else{
                //不存在则添加
                $this->add();
            }
        }
    }

    /**
     * @NodeAnnotation(
     *     title="获取文章支持的用户",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function get_look_user()
    {

        $where = [];

        $keyword = $this->request->param("keyword",'');
        if($keyword) array_push($where,["phone|username|nickname","like","%{$keyword}%"]);
        $article_id = $this->request->param("article_id",0,"intval");

        $LookUser = (new UseLookAccess())->where('article_id',$article_id)
            ->select();

        $userList = User::field("id as value,username as name")
            ->where($where)
            ->paginate(10)
            ->toArray();

        foreach ($userList['data'] as $k=>$v)
        {
            $userList['data'][$k]['selected'] = false;

            foreach ($LookUser as $key=>$value)
            {
                if($v['value']==$value['user_id']&& !empty($value))
                {
                    $userList['data'][$k]['selected'] = true;
                }
            }
        }
        return json($userList);
    }

    /**
     * @NodeAnnotation(
     *     title="生成pdf文件",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function pdf()
    {
        $article_id = $this->request->param("id",0,"intval");

        if(!$article_id) $this->error("请选择所需要生成的PDF数据");
        $articleData = $this->model->where("id",$article_id)->with("user")->field("*,post_title as title,post_content as content")->find();
        if(!$articleData) $this->error("该数据没有被找到，或者已被删除");
        $option = get_user_option("download_setting",$articleData['user_id']);
        $logo   = str_replace("\\","/",_get_image_preview_url($option['watermark']));
        /*$articleData['post_content'] =   cmf_replace_content_file_url($articleData['post_content']);
        $pdfFilename = str_replace("\\","/",_get_image_preview_url($articleData['more']['attachments'][0]));
        pdfView($pdfFilename);
        pdf2png($pdfFilename,'');
        return pdfParser($pdfFilename);
        die;*/
        return importPdf($articleData['post_title'],$articleData['post_content'],time(),$logo,$option['header'],$option['footer']);
    }

    /**
     * @NodeAnnotation(
     *     title="生成word文件",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function word()
    {
        $article_id = $this->request->param("id",0,"intval");
        if(!$article_id) $this->error("请选择所需要生成的PDF数据");
        $articleData = $this->model->where("id",$article_id)->with("user")->field("*,post_title as title,post_content as content")->find();
        if(!$articleData) $this->error("该数据没有被找到，或者已被删除");
        $option = get_option("site_info");
        $logo   = $option['photo'];
        return importWord($articleData['post_title'],$articleData['post_content'],$logo);
    }


    /**
     * @NodeAnnotation(
     *     title="推送服务",
     *     parent="post/admin.post",
     *     MenuRoot="post/admin.index",
     *     is_menu = 0
     * )
     */
    public function push()
    {
        $type = $this->request->param("type");

        $data = $this->model->where("id",$this->request->param("id",0))->find();

        $title = $data['post_title'];
        $content = '';
        switch ($type)
        {
            case 'email':
                $content = url('post/home.index/content',['id'=>$data['id']],'',true);
                break;

            case 'sms':
                $this->error("暂不支持短信推送");
                break;

            case 'official_accounts':
                $this->error("暂不支持公众号推送");

                break;
        }
        \think\Queue::push('\app\common\service\QueueClientService@send', [
            "title"  => $title,
            "content"=> $content,
            "type"   => $type
        ], "");

        $this->success("推送成功");

    }


}